import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

import Layout from '@/layout'
import {constantRoutes} from './router'
import {routerMenusList} from '@/api/api.verify.js'


NProgress.configure({ showSpinner: false }) // NProgress 程序配置

const whiteList = ['/login'] // 白名单重定向

router.beforeEach(async(to, from, next) => {
  // 开始进度条
  NProgress.start()

  // 设置页面标题
  document.title = getPageTitle(to.meta.title)

  // 确定用户是否已登录
  if (getToken()) {
    if (to.path === '/login') {
      // 如果已登录，请重定向到主页
      next({ path: '/' })
      NProgress.done()
    } else {
      if (localStorage.getItem('addRouter')) {
        if(router.options.routes.length==constantRoutes.length){//判断页面是否刷新
          loadMenus(next, to)
        }else{
          next()
        }
      } else {
        loadMenus(next, to)
      }
    }
  } else {
    /* 如果没有token */

    if (whiteList.indexOf(to.path) !== -1) {
      // 在免费登录白名单中，直接进入
      next()
    } else {
      // 其他没有访问权限的页面将重定向到登录页面。
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // 完成进度条
  NProgress.done()
})

export const filterAsyncRouter = (routers) => { // 遍历后台传来的路由字符串，转换为组件对象
  return routers.filter(router => {
    delete router.code
    delete router.id
    delete router.level
    delete router.link
    delete router.method
    delete router.pid
    delete router.sort
    delete router.style
    delete router.type
    delete router.scope
    if (router.component) {
      if (router.component === 'Layout') { // Layout组件特殊处理
        router.component = Layout
      } else {
        // const component = router.component
        // router.component = loadView(component)
        router.component = loadView(router.component)
      }
    }
    if (router.children && router.children.length) {
      router.children = filterAsyncRouter(router.children)
    }else if(router.children==null||router.children.length==0){
      delete router.children
      delete router.alwaysShow
    }
    return true
  })
}

export const loadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve)
}

export const loadMenus = (next, to) => {
    let addMenu=JSON.parse(localStorage.getItem('addRouter'))
    if(addMenu){
      const asyncRouter = filterAsyncRouter(addMenu)
      let datas=constantRoutes.concat(asyncRouter)
      router.options.routes=datas
      router.addRoutes(asyncRouter)
      next({ ...to, replace: true })
    }else{
      let data={}
      routerMenusList(data).then(d=>{
        let menu=d.data.menus
        let btnList=d.data.btns
        localStorage.removeItem('addRouter')
        menu.push({ path: '*', redirect: '/404', hidden: true })
        localStorage.setItem('addRouter',JSON.stringify(menu))
        localStorage.setItem('btnList',JSON.stringify(btnList));
        const asyncRouter = filterAsyncRouter(menu)
        let datas=constantRoutes.concat(asyncRouter)
        router.options.routes=datas
        router.addRoutes(asyncRouter) // 动态添加可访问路由表
        next({ ...to, replace: true })
      })
    }
}